package com.issc.framework.proxy;

import com.issc.framework.annotation.Transaction;
import com.issc.framework.helper.DataBaseHelper;

import java.lang.reflect.Method;

public class TransactionProxy implements Proxy {
    private static final ThreadLocal<Boolean> FLAG_HOLDER = new ThreadLocal<Boolean>() {
        @Override
        protected Boolean initialValue() {
            return false;
        }
    };

    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result = null;
        boolean flag = FLAG_HOLDER.get();
        Method method = proxyChain.getTargetMethod();
        if (!flag && method.isAnnotationPresent(Transaction.class)) {
            FLAG_HOLDER.set(true);
            try {
                DataBaseHelper.beginTransaction();
                result = proxyChain.doProxyChain();
                DataBaseHelper.commitTransaction();
            } catch (Exception e) {
                DataBaseHelper.rollbackTransaction();
                e.printStackTrace();
            }finally {
                FLAG_HOLDER.remove();
            }
            }else {
            result=proxyChain.doProxyChain();
        }return result;
    }

}
